package edu.friday.common.security.service;

import edu.friday.common.constant.UserConstants;
import edu.friday.common.enums.UserStatus;
import edu.friday.common.exception.BaseException;
import edu.friday.common.security.LoginUser;
import edu.friday.model.SysUser;
import edu.friday.model.vo.SysUserVO;
import edu.friday.service.ISysUserService;
import edu.friday.utils.BeanUtils;
import edu.friday.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查询用户信息,判断账户状态并记打印日志
        SysUser sysUser = iSysUserService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            log.info("登录用户：{} 不存在", username);
            throw new UsernameNotFoundException(username + "用户名不存在");
        } else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        else if(UserStatus.DISABLE.getCode().equals(sysUser.getStatus())){
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        //2.获取权限信息
        SysUserVO sysUserVO = new SysUserVO();
        BeanUtils.copyProperties(sysUser,sysUserVO);
        Set<String> perm = sysPermissionService.selectMenuPermission(sysUserVO);
        //3.返回封装好信息的UserDetail对象
        return new LoginUser(sysUserVO,perm);
    }
}
